#include "Hex.h"
#include <sstream>
#include <cstdlib>

const int format[] = {10, 11, 12, 13, 14, 15};
const int tamrof[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

int htoi (const string& text) //convert two digit hex string to integer
{
	int st = 0, nd = 0;
	char a = text[0], b = text[1];
	if (int(a) >= 97)
		st = 16 * format[int(a) - 97];
	else st = 16 * tamrof[int(a) - 48];
	
	if (int(b) >= 97)
		nd = format[int(b) - 97];	
	else nd = tamrof[int(b) - 48];

	return st + nd;
}

string Hex::encode(const string& text)
{
	std::stringstream ss;
	string chr, h;

	for (unsigned int i = 0; i < text.length(); i++)
	{
		ss.clear();
		ss.str("");
		ss<<std::hex<<int(text[i]);

		ss>>chr;
		h += chr;
		chr = "";
	}	
	return h;
}

string Hex::decode(const string& text)
{
	string* temp = new string[text.length()];
	string output = "";
	for (unsigned int i = 0; i < text.length(); i+=2)
	{
		temp[i] = text[i];
		temp[i] += text[i + 1];
		output += char(htoi(temp[i]));
	}
	delete [] temp;
	return output;
}
